package controller

import (
	"mini-app/config/mysql"
	"mini-app/internal/app/admin/service"
	"mini-app/internal/dao"
	"mini-app/internal/models"
	"strconv"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type Announcement struct{}

func (Announcement) Create(c *gin.Context) {
	var params models.Announcement
	c.ShouldBindBodyWith(&params, binding.JSON)
	id, err := service.Announcement{}.Create(c.Request.Context(), params)
	response.JSON(c, gin.H{
		"id": id,
	}, err)
}

func (Announcement) Update(c *gin.Context) {
	var params struct {
		ID        string `json:"id"`
		Name      string `json:"name"`
		Content   string `json:"content"`
		StartTime int64  `json:"start_time"`
		EndTime   int64  `json:"end_time"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	err := service.Announcement{}.Update(
		c.Request.Context(),
		params.ID,
		params.Name,
		params.Content,
		params.StartTime,
		params.EndTime,
	)
	response.JSON(c, nil, err)
}

func (Announcement) Delete(c *gin.Context) {
	var params struct {
		ID string `json:"id"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	err := service.Announcement{}.Delete(c.Request.Context(), params.ID)
	response.JSON(c, nil, err)
}

func (Announcement) List(c *gin.Context) {
	name := c.Query("name")
	status, _ := strconv.Atoi(c.Query("status"))
	page, _ := strconv.Atoi(c.Query("page"))
	limit, _ := strconv.Atoi(c.Query("limit"))
	list, total := service.Announcement{}.List(c.Request.Context(), name, status, page, limit)
	response.JSON(c, gin.H{
		"list":  list,
		"total": total,
	}, nil)
}

func (Announcement) Detail(c *gin.Context) {
	var err error
	detail := dao.Announcement{}.Detail(c.Request.Context(), mysql.NewDB(), c.Query("id"))
	if detail == nil {
		err = errorx.New("公告不存在", -1)
	}
	response.JSON(c, detail, err)
}
